# 个人中心
import logging,re
from flask import current_app, jsonify,session,request,g
from iHome import constants,db
from iHome.models import User
from iHome.utils.commony import login_required
from iHome.utils.qiniu_storage import storage
from iHome.utils.response_code import RET
from . import profile_blu



@profile_blu.route('/user_information')
@login_required
def user_profile_login():
    """判断用户是否有登录"""
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    try:
        user = User.query.filter_by(id=user.id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR, errmsg = '数据查询错误')


    return jsonify(errno=RET.OK, errmsg='OK', data=user.to_dict())



@profile_blu.route('/user/avatar', methods = ["POST"])
@login_required
def upload_avatar():
    """上传图片"""

    # 判断是否登录
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 上传
    try:
        avatar = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.erroe(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        avatar_url = storage(avatar)
    except Exception as e:
        current_app.logger.erro(e)
        return jsonify(errno = RET.THIRDERR, errmsg = "上传图片出错")

    user.avatar_url = avatar_url
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR, errmsg = "数据库操作失败")


    # 3.更新当前用户头像地址信息
    user.id = g.user.id
    try:
        User.query.filter_by(id = user.id).update({'avatar_url': avatar_url})
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno = RET.DBERR, errmsg = '图片保存失败')
    else:
        # 4.返回用户头像地址
        avatar_url = constants.QINIU_DOMIN_PREFIX + avatar_url
        return jsonify(errno = RET.OK, errmsg = '图片上传成功', data = {"avatar_url": avatar_url})




@profile_blu.route('/user/name', methods=['POST'])
@login_required
def user_name():
    """个人中心修改"""

    # 判断是否登录
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    data_dict = request.json
    user_name = data_dict.get('name')
    print(user_name)

    if not user_name:
        return jsonify(errno = RET.NODATA, errmsg = "无数据")

    # 查询出指定user并更新 name 属性
    try:
        User.query.filter_by(id = g.user.id).update({'name': user_name})
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR, errmsg = '更新数据出错')
    else:
        # 返回修改结果
        return jsonify(errno = RET.OK, errmsg = '修改成功')



@profile_blu.route('/user/auth', methods=['POST','GET'])
@login_required
def set_auth():
    if request.method == "POST":
        """实名认证"""
        # 判断是否登录
        user = g.user
        if not user:
            return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

        data_dict = request.json
        real_name = data_dict.get('real_name')  # 姓名
        id_card = data_dict.get('id_card')   # 身份证

        if not real_name and not id_card:  # 判空
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')


        # 验证身份证号码  正则
        id_card_verification = re.match("(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)", id_card)

        if id_card_verification:
            user_id = g.user_id
            # 验证身份证号码是否为False,上传到数据库
            try:
                User.query.filter_by(id=user_id).update({'real_name': real_name, 'id_card': id_card})
                db.session.commit()
            except Exception as e:
                logging.error(e)
                db.session.rollback()
                return jsonify(errno = RET.DBERR, errmsg = '认证信息保存失败')
            else:
                return jsonify(errno = RET.OK, errmsg = '认证信息保存成功')
        else:
            return jsonify(errno = RET.DBERR, errmsg = '身份证有误')
    elif request.method == "GET":
        """
        获取用户实名认证信息
        :return:
        """
        # 实名认证
        user = g.user
        if not user:
            return jsonify(errno=RET.SESSIONERR, errmsg='用户不存在')

        user_id = g.user_id
        try:
            user = User.query.filter_by(id=user_id).first()
        except Exception as e:
            logging.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

        # 如果用户不存在
        if user is None:
            return jsonify(errno=RET.SESSIONERR, errmsg='用户不存在')

        return jsonify(errno=RET.OK, errmsg='OK', data=user.auth_to_dict())



@profile_blu.route('/user_login',methods=['GET'])
@login_required
def user_login():
    """判断是否登录"""
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    name = session.get("name")
    avatar = user.avatar_url

    if not name:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    else:
        return jsonify(errno=RET.OK, errmsg='用户已登录', data={'name': name, 'avatar': constants.QINIU_DOMIN_PREFIX + avatar})
